package com.atguigu.gulimall.product.service.impl;

import com.atguigu.common.constant.ProductConstant;
import com.atguigu.common.utils.PageUtils;
import com.atguigu.common.utils.Query;
import com.atguigu.gulimall.product.dao.AttrDao;
import com.atguigu.gulimall.product.entity.AttrAttrgroupRelationEntity;
import com.atguigu.gulimall.product.entity.AttrEntity;
import com.atguigu.gulimall.product.entity.AttrGroupEntity;
import com.atguigu.gulimall.product.entity.CategoryEntity;
import com.atguigu.gulimall.product.service.AttrAttrgroupRelationService;
import com.atguigu.gulimall.product.service.AttrGroupService;
import com.atguigu.gulimall.product.service.AttrService;
import com.atguigu.gulimall.product.service.CategoryService;
import com.atguigu.gulimall.product.vo.AttrAttrgroupRelationVO;
import com.atguigu.gulimall.product.vo.AttrResponseVO;
import com.atguigu.gulimall.product.vo.AttrVO;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;


@Service("attrService")
public class AttrServiceImpl extends ServiceImpl<AttrDao, AttrEntity> implements AttrService {
    @Autowired
    private AttrGroupService attrGroupService;
    @Autowired
    private AttrAttrgroupRelationService relationService;
    @Autowired
    private CategoryService categoryService;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<AttrEntity> page = this.page(
                new Query<AttrEntity>().getPage(params),
                new QueryWrapper<AttrEntity>()
        );

        return new PageUtils(page);
    }

    @Override
    public void saveAttr(AttrVO attr) {

        AttrEntity attrEntity = new AttrEntity();
        // 将VO属性拷贝至PO
        BeanUtils.copyProperties(attr, attrEntity);
        // 保存商品属性信息
        this.save(attrEntity);

        if (attrEntity.getAttrType() == ProductConstant.AttrEnum.ATTR_TYPE_BASE.getCode() &&
                attr.getAttrGroupId() != null) {
            // 保存属性分组关联关系
            AttrAttrgroupRelationEntity relationEntity = new AttrAttrgroupRelationEntity();
            relationEntity.setAttrId(attrEntity.getAttrId());
            relationEntity.setAttrGroupId(attr.getAttrGroupId());

            relationService.save(relationEntity);
        }
    }

    @Override
    public PageUtils queryAttrBasePage(Map<String, Object> params, Long catelogId, String attrType) {
        int type = "base".equalsIgnoreCase(attrType) ?
                ProductConstant.AttrEnum.ATTR_TYPE_BASE.getCode() :
                ProductConstant.AttrEnum.ATTR_TYPE_SALE.getCode();
        // 获取搜索框的值，并添加到QueryWrapper中
        QueryWrapper<AttrEntity> wrapper = new QueryWrapper<AttrEntity>().eq("attr_type", type);
        String key = (String) params.get("key");

        if (!StringUtils.isEmpty(key)) {
            wrapper.and(obj -> obj.eq("attr_id", key).or().like("attr_name", key));
        }

        if (catelogId != 0) {
            wrapper.eq("catelog_id", catelogId);
        }

        IPage<AttrEntity> page = this.page(
                new Query<AttrEntity>().getPage(params),
                wrapper
        );

        PageUtils pageUtils = new PageUtils(page);

        List<AttrEntity> records = page.getRecords();
        List<AttrResponseVO> voList = records.stream().map(attrEntity -> {
            // 创建一个AttrResponseVO对象
            AttrResponseVO attrResponseVO = new AttrResponseVO();
            BeanUtils.copyProperties(attrEntity, attrResponseVO);

            // 若为基础属性，则获取其分组
            if ("base".equalsIgnoreCase(attrType)) {
                // 获取分组名称
                AttrAttrgroupRelationEntity relationEntity = relationService.getOne(new QueryWrapper<AttrAttrgroupRelationEntity>().eq("attr_id", attrEntity.getAttrId()));
                if (relationEntity != null && relationEntity.getAttrGroupId() != null) {
                    AttrGroupEntity attrGroupEntity = attrGroupService.getById(relationEntity.getAttrGroupId());
                    attrResponseVO.setGroupName(attrGroupEntity.getAttrGroupName());
                }
            }
            // 获取分类名称
            CategoryEntity categoryEntity = categoryService.getById(attrEntity.getCatelogId());
            attrResponseVO.setCatelogName(categoryEntity.getName());

            return attrResponseVO;
        }).collect(Collectors.toList());

        pageUtils.setList(voList);
        return pageUtils;
    }

    @Override
    public AttrResponseVO getAttrInfo(Long attrId) {
        AttrEntity attr = this.getById(attrId);
        AttrResponseVO attrResponseVO = new AttrResponseVO();
        BeanUtils.copyProperties(attr, attrResponseVO);

        // 获取属性的分组信息
        AttrAttrgroupRelationEntity relationEntity = relationService.getOne(new QueryWrapper<AttrAttrgroupRelationEntity>().eq("attr_id", attrId));
        if (relationEntity != null) {
            attrResponseVO.setAttrGroupId(relationEntity.getAttrGroupId());
            // 获取属性分组的名称
            AttrGroupEntity attrGroupEntity = attrGroupService.getById(relationEntity.getAttrGroupId());
            if (attrGroupEntity != null) {
                attrResponseVO.setGroupName(attrGroupEntity.getAttrGroupName());
            }
        }

        // 获取分类路径信息
        Long[] catelogPath = categoryService.findCatalogPath(attrResponseVO.getCatelogId());
        attrResponseVO.setCatelogPath(catelogPath);
        CategoryEntity categoryEntity = categoryService.getById(attrResponseVO.getCatelogId());
        if (categoryEntity != null) {
            attrResponseVO.setCatelogName(categoryEntity.getName());
        }

        return attrResponseVO;
    }

    @Override
    public void updateAttr(AttrResponseVO attr) {
        AttrEntity attrEntity = new AttrEntity();
        BeanUtils.copyProperties(attr, attrEntity);
        // 更新属性信息
        this.updateById(attrEntity);

        if (attrEntity.getAttrType() == ProductConstant.AttrEnum.ATTR_TYPE_BASE.getCode()) {
            // 更新属性-分组关联信息
            AttrAttrgroupRelationEntity relationEntity = new AttrAttrgroupRelationEntity();
            relationEntity.setAttrGroupId(attr.getAttrGroupId());
            relationEntity.setAttrId(attr.getAttrId());

            // 判断是否存在关联关系
            if (relationService.count(new QueryWrapper<AttrAttrgroupRelationEntity>().eq("attr_id", attr.getAttrId())) > 0) {
                relationService.update(relationEntity, new UpdateWrapper<AttrAttrgroupRelationEntity>().eq("attr_id", attr.getAttrId()));
            } else {
                relationService.save(relationEntity);
            }
        }
    }

    @Override
    public List<AttrEntity> getRelationAttr(Long attrgroupId) {
        // 获取属性-分组的关联关系
        List<AttrAttrgroupRelationEntity> list = relationService.list(new QueryWrapper<AttrAttrgroupRelationEntity>().eq("attr_group_id", attrgroupId));

        // 获取分组的id
        List<Long> attrIdList = list.stream().map(AttrAttrgroupRelationEntity::getAttrId).collect(Collectors.toList());

        return CollectionUtils.isEmpty(attrIdList) ? null : this.listByIds(attrIdList);
    }

    @Override
    public void deleteRelationAttr(AttrAttrgroupRelationVO[] relationVOS) {
        List<AttrAttrgroupRelationEntity> entities = Arrays.stream(relationVOS).map(relationVO -> {
            AttrAttrgroupRelationEntity relationEntity = new AttrAttrgroupRelationEntity();

            relationEntity.setAttrId(relationVO.getAttrId());
            relationEntity.setAttrGroupId(relationVO.getAttrGroupId());

            return relationEntity;
        }).collect(Collectors.toList());

        relationService.deleteBatchRelationAttr(entities);
    }

    @Override
    public PageUtils getRelationNoattr(Long attrgroupId, Map<String, Object> params) {
        // 获取分类id
        AttrGroupEntity attrGroupEntity = attrGroupService.getOne(new QueryWrapper<AttrGroupEntity>().eq("attr_group_id", attrgroupId));
        Long catelogId = attrGroupEntity.getCatelogId();

        // 获取该分组的属性id
        List<AttrAttrgroupRelationEntity> list = relationService.list(new QueryWrapper<AttrAttrgroupRelationEntity>().eq("attr_group_id", attrgroupId));
        List<Long> attrIds = list.stream().map(AttrAttrgroupRelationEntity::getAttrId).collect(Collectors.toList());

        // 获取该分类下未分组的属性
        QueryWrapper<AttrEntity> queryWrapper = new QueryWrapper<AttrEntity>().eq("catelog_id", catelogId)
                .eq("attr_type", ProductConstant.AttrEnum.ATTR_TYPE_BASE.getCode());
        if (!CollectionUtils.isEmpty(attrIds)) {
            queryWrapper.notIn("attr_id", attrIds);
        }

        String key = (String) params.get("key");
        if (key != null) {
            queryWrapper.and(wrapper -> wrapper.eq("attr_id", key).or().like("attr_name", key));
        }
        IPage<AttrEntity> page = this.page(new Query<AttrEntity>().getPage(params), queryWrapper);

        return new PageUtils(page);
    }

    @Override
    public List<Long> queryAttrBySearch(List<Long> attrIds) {

        return baseMapper.selectAttrBySearch(attrIds);
    }

}